package com.hantang.web.json.handlers;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.glassfish.grizzly.http.server.Request;
import org.glassfish.grizzly.http.server.Response;

import com.google.gson.Gson;
import com.hantang.web.dao.NewMessageDao;
import com.hantang.web.data.NewMessageData;
import com.hantang.web.json.ds.MetaData;
import com.hantang.web.json.ds.NewMessage;
import com.hantang.web.json.res.NewMessagesRes;

public class GetNewsHandler extends AbstractHandler {

	private static Logger logger = Logger.getLogger(GetNewsHandler.class);
	
	@Override
	public String doService(Request req, Response resp) throws Exception {
		
		String lastId = req.getParameter("lastId");
		String count = req.getParameter("count");
		
		String sret = handleServlet(lastId, count);
		return sret;
	}

	public static String handleServlet(String lastId, String count) {
		NewMessagesRes resss = new NewMessagesRes();

		logger.info(lastId + ": " + count);
		if(lastId == null){
			lastId = ""+Long.MAX_VALUE;//
		}
		if(count == null){
			count = "10";
		}
		try {
			long fId = Long.valueOf(lastId.trim());
			int icount = Integer.valueOf(count.trim());
			List<NewMessage> datas = handle(fId, icount);
			resss.setData(datas);
			resss.setMeta(new MetaData(MetaData.META_DATA_SUCCESS_CODE, "SUCC"));
		} catch (Exception e) {
			logger.error("doService Exception.", e);
			resss.setMeta(new MetaData(MetaData.META_DATA_FAILED_CODE,"Failed"));
		}
 
		Gson gson = new Gson();
		String sret = gson.toJson(resss);
		return sret;
	}
	
	public static List<NewMessage> handle(long lastId, int count)
	{
		
		NewMessageDao dao = new NewMessageDao();
		List<NewMessageData> datas = dao.queryDatas(lastId, count);
		List<NewMessage> jsons  = null;
		if(datas != null){
			jsons = new ArrayList<NewMessage>();
			for(NewMessageData data : datas)
			{
				jsons.add(NewMessage.convertData2Json(data));
			}
			
		}
		
		return jsons;
		 
	}
	
	

}
